package org.realteam.webapp.webconfig;

import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * Code-based alternative to web.xml for use within Servlet 3.0+ environments. See
 * {@link WebApplicationInitializer} Javadoc for complete details. 
 * 
 * @author Harry
 * @version 1.0 Created On：2011-12-25 下午2:50:33
 */
public class GreenhouseWebAppInitializer implements WebApplicationInitializer {
	public void onStartup(ServletContext sc) throws ServletException {
		System.out.println("GreenhouseWebAppInitializer.onStartup()");
		// Create the 'root' Spring application context
		AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
		root.scan("com.springsource.greenhouse.config");
		root.getEnvironment().setDefaultProfiles("embedded");

		// Manages the lifecycle of the root application context
		sc.addListener(new ContextLoaderListener(root));
		// Allows attributes to be accessed on the next request
		// sc.addFilter("flashMapFilter",
		// FlashMapFilter.class).addMappingForUrlPatterns(null, false, "/*");

		sc.addFilter("hiddenHttpMethodFilter", HiddenHttpMethodFilter.class).addMappingForUrlPatterns(null, false, "/*");
		// Secures the application
		//sc.addFilter("securityFilter", new DelegatingFilterProxy("springSecurityFilterChain")).addMappingForUrlPatterns(null, false, "/*");

		// Handles requests into the application
		ServletRegistration.Dynamic appServlet = sc.addServlet("appServlet", new DispatcherServlet(new GenericWebApplicationContext()));
		appServlet.setLoadOnStartup(1);
		Set<String> mappingConflicts = appServlet.addMapping("/");
		if (!mappingConflicts.isEmpty()) {
			throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
		}
	}
}
